package com.mxprojects.gui
{
	import com.mxprojects.constructors.ImageDisplay;
	import com.mxprojects.io.Config;
	import com.mxprojects.io.TagParser;
	import com.mxprojects.language.Language;
	import com.mxprojects.language.Word;
	import com.mxprojects.views.Posts;
	import com.mxprojects.views.ProfileWindow;
	
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.TextEvent;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	
	public class PostItem extends BaseForumElement
	{
		private const AVATAR_POST_COUNT_GAP:int = 5;
		private const DIVIDER_COUNT:int = 1;
				
		public static var BACKGROUND_COLOR:int = -1; 
		
		private var POST_JOIN_GAP:Number;
		
		public var author:TextField;
		public var title:TextField;
		public var postCount:TextField;
		public var regDate:TextField;
		public var message:TextField;
		public var signature:TextField;
		public var postedDate:TextField;
		public var postOptions:PostOptions;
		public var isEditMode:Boolean = false;
		
		//setup the vars to hold on to stuff for mouse clicks and junk
		private var postAuthor:String;
		private var defaultHeight:int;
		private var postHeader:PostHeader;
		private var avatar:Loader = new Loader();
		private var images:Array = new Array();
		private var originalMessage:String;
		
		public function PostItem(){}
		
		public function addImage(location:String, description:String, imgWidth:int, imgHeight:int):void {
			/********************************************************************************************** 
			 * Adobe doesn't think images should be on thier own line in a text field
			 * From the doc: "Text automatically flows around images you embed in text fields. 
			 * You must set the text field to be multiline to wrap text around an image."
			 * So that means we gotta make an image display constructor to place below the message *grumble*
			 ***********************************************************************************************/
			var imageDisplay:ImageDisplay = new ImageDisplay(location, description, imgWidth, imgHeight);
			imageDisplay.name = "image" + images.length;
			images.push(imageDisplay);
		}
		
		public function display(postID:int, message:String, author:String, authorID:int, title:String, postCount:String, regDate:String, 
								postedDate:String, avatarURL:String, signature:String, postHeader:PostHeader):void {
			
			//set the visual elements if the css is there
			this.author.styleSheet = Styles.css;
			this.title.styleSheet = Styles.css;
			this.postCount.styleSheet = Styles.css;
			this.regDate.styleSheet = Styles.css;
			this.postedDate.styleSheet = Styles.css;
			this.message.styleSheet = Styles.css;
			this.signature.styleSheet = Styles.css;
			
			//setup the header
			this.postHeader = postHeader;
						
			//setup the textfields
			var htmlMessage:String = TagParser.convertToHtml(message);
			this.message.x = postHeader.getDivider(0).x + Config.TEXT_PADDING;
			this.message.y = Config.TEXT_PADDING;
			this.message.htmlText = "<span class=\"postMessage\">" + htmlMessage + "</span>";
			this.originalMessage = message;
			
			//put up any [quote] blocks
			TagParser.parseQuote(this.message);
			
			//get the background colour
			if(BACKGROUND_COLOR == -1){
				var bgColour:BitmapData = new BitmapData(1, 1, false);
				bgColour.draw(background);
				
				//this stores the int so that we can convert to hex in the emote class .toString(16)
				BACKGROUND_COLOR = bgColour.getPixel(0, 0);
				
				//clean up
				bgColour = null;
			}
			
			
			//check for a signature
			if(signature != ""){
				this.signature.htmlText = "<span class=\"postDivider\">" + Config.MESSAGE_DIVIDER + "</span><br>" +  "<span class=\"postSignature\">" + TagParser.convertToHtml(signature) + "</span>";
				this.signature.autoSize = TextFieldAutoSize.LEFT;
			}
			
			//if all the message text is there, autosize it
			this.message.autoSize = TextFieldAutoSize.LEFT;
			
			//setup the author and make the name view the profile
			this.author.htmlText = "<a href=\"event:"+author+","+authorID+"\"><span class=\"postAuthor\">" + author + "</span></a>";
			this.author.addEventListener(TextEvent.LINK, viewProfile, false, 0, true);
			postAuthor = author;
			
			this.title.htmlText = "<span class=\"postTitle\">" + title + "</span>";
			
			this.postCount.htmlText = "<span class=\"postPostCount\">" + Language.main(Word.POSTS) + ": " + postCount + "</span>";
			this.regDate.htmlText = "<span class=\"postRegDate\">" + Language.main(Word.JOINED) + ": " + regDate + "</span>";
			POST_JOIN_GAP = this.regDate.y - this.postCount.y;
			
			this.postedDate.htmlText = "<span class=\"postPostedDate\">" + Language.main(Word.POSTED) + ": " + postedDate + "</span>";
			
			//take a snapshot of the current height incase the text is small
			defaultHeight = background.height;
			
			//check if we have an avatar pic
			if(avatarURL != ""){
				avatar.load(new URLRequest(avatarURL));
				avatar.contentLoaderInfo.addEventListener(Event.COMPLETE, addAvatar, false, 0, true);
				
				//if there is a URL, but for some reason it's messed up, don't do anything
				avatar.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, badAvatar, false, 0, true);
			}
			
			//setup defaults from CSS
			super.init(".postBackground", DIVIDER_COUNT);
			
			//setup the post options
			postOptions.display(postID, authorID);
			
			//move stuff where it needs to be
			placeStuff();
		}
		
		override public function resize():void {
			placeStuff();
			super.resize();
			postOptions.resize();
		}
		
		public function getOriginalMessage():String {
			return this.originalMessage;
		}
		
		public function setOriginalMessage(text:String):void {
			this.originalMessage = text;
		}
		
		private function placeStuff():void {
			message.width = MXP3.wStage - Config.TEXT_PADDING - message.x;
			signature.width = message.width;
			
			//grab the height of the text, shut off auto size and then lock the height.
			//this makes it so the text block doesn't scroll
			var tempHeight:int = message.textHeight;
			message.autoSize = TextFieldAutoSize.NONE;
			message.height = tempHeight + Config.TEXT_PADDING;
			
			//do the same thing for the signature
			var tempSigHeight:int = signature.textHeight;
			signature.autoSize = TextFieldAutoSize.NONE;
			signature.height = tempSigHeight + Config.TEXT_PADDING;
			
			
			//stretch out the BG
			background.height = Math.floor(message.y + message.height + Config.TEXT_PADDING);
			
			//check for images
			if(images.length > 0){
				for(var i:int = 0; i < images.length; i++){
					var image:ImageDisplay = images[i];
					if(!getChildByName("image"+i)){
						addChild(image);
					}
					
					if(i == 0){
						//this is the first image so it goes right after the message
						image.y = message.y + message.height + Config.TEXT_PADDING;
						image.x = getDivider(0).x + Config.TEXT_PADDING;
					}else{
						//if it's the next image get the previous image height and slap it in after it
						var prevImage:ImageDisplay = images[i-1];
						image.y = prevImage.y + prevImage.getHeight() + Config.TEXT_PADDING;
						image.x = prevImage.x;
					}
					
					//see if the image is too large
					if(image.startWidth > MXP3.wStage - image.x - Config.TEXT_PADDING){
						image.setWidth(MXP3.wStage - image.x - Config.TEXT_PADDING);
					}else{
						image.setWidth(image.startWidth);
					}
					
					//increase the bg height
					background.height += image.getHeight() + Config.TEXT_PADDING;
				}
			}
			
			//extend the bg for the sig box
			background.height += signature.height + Config.TEXT_PADDING;
			
			//place the post options in there
			background.height += postOptions.height;
			
			if(background.height < defaultHeight){
				background.height = defaultHeight;
			}
			
			getDivider(0).x = postHeader.getDivider(0).x;
			getDivider(0).height = background.height;
			
			//set the options
			postOptions.x = getDivider(0).x;
			postOptions.y = background.height - postOptions.height;
			
			//place the signature box at the bottom of everything
			signature.x = getDivider(0).x + Config.TEXT_PADDING;
			signature.y = postOptions.y - signature.height;
			
			postedDate.y = background.height - postedDate.height;
			
			//parse the emoticons
			if(!isEditMode){
				Emoticons.parse(message, BACKGROUND_COLOR, "postMessage");
			}
		}
		
		private function addAvatar(event:Event):void {
			//this will put the avatar in the right place and also move the text fields down
			
			//position it
			//avatar.x = Math.round(divider1.x/2 - avatar.width/2);
			avatar.x = author.x;
			avatar.y = Math.round(title.y + title.height);
			addChild(avatar);
			
			//fix the post count and join date Y positions
			postCount.y = Math.round(avatar.y + avatar.height + AVATAR_POST_COUNT_GAP);
			regDate.y = postCount.y + POST_JOIN_GAP;
		}
		
		private function viewProfile(event:TextEvent):void {
			//break up the text since we are passing username AND id
			var chunks:Array = event.text.split(",");
			ProfileWindow.view(chunks[0], chunks[1]);
		}
		
		private function badAvatar(event:Event):void {
			//this means that there was an issue with someone's avatar, should probably clean up
			trace(postAuthor, "has bad URL for avatar");
		}
	}
}